package jw.webapi.order;

import jw.model.agent.WxAgent;
import jw.model.order.WxOrder;
import jw.model.order.WxOrderCommodity;
import jw.model.order.WxShoppingCart;
import jw.model.product.WxProColSize;
import jw.model.product.WxProduct;
import jw.model.product.WxProductImage;
import jw.repository.agent.WxAgentRepository;
import jw.repository.order.WxOrderCommodityRepository;
import jw.repository.order.WxOrderRepository;
import jw.repository.order.WxShoppingCartRepository;
import jw.repository.product.WxProColSizeRepository;
import jw.repository.product.WxProductImageRepository;
import jw.repository.product.WxProductRepository;
import jw.util.OrderNumberUtil;
import jw.util.ResponseUtil;
import org.apache.commons.collections.map.HashedMap;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.math.BigDecimal;
import java.util.*;


/**
 * 购物车接口
 * Created by 天赐美颜郭德纲 on 2020/01/07.
 */
@Controller
@CrossOrigin
@RequestMapping("wx/cart/")
public class ShoppingCartWebApi {

    @Autowired
    private WxProColSizeRepository wxProColSizeRepository;

    @Autowired
    private WxProductRepository wxProductRepository;

    @Autowired
    private WxShoppingCartRepository wxShoppingCartRepository;

    @Autowired
    private WxAgentRepository wxAgentRepository;

    @Autowired
    private WxProductImageRepository wxProductImageRepository;
    @Autowired
    WxOrderCommodityRepository wxOrderCommodityRepository;
    @Autowired
    WxOrderRepository wxOrderRepository;

    /**
     * 添加购物车
     *
     */
    @RequestMapping("addCart")
    @ResponseBody
    public Object addCart(@RequestBody String data) {
        JSONObject jsonObject = new JSONObject(data);
        if(jsonObject.isNull("count") || jsonObject.isNull("colSizeId") || jsonObject.isNull("price") || jsonObject.isNull("openId")){
            return ResponseUtil.badArgumentValue();
        }
        String openId = jsonObject.getString("openId");
        Integer colSizeId = jsonObject.getInt("colSizeId");
        Integer count = jsonObject.getInt("count");
        Integer price = jsonObject.getInt("price");
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.unlogin();
        }
        WxProColSize colSize = wxProColSizeRepository.findOne(colSizeId);
        if (colSize == null){
            return ResponseUtil.fail(2,"该颜色尺码无货");
        }
        WxProduct product  = wxProductRepository.findByNo(colSize.getProductNo());
        if (product == null) {
            return ResponseUtil.fail(2,"产品出错");
        }
        WxShoppingCart shoppingCart = wxShoppingCartRepository.findByAgentIdAndSku(agent.getId(),colSize.getSku());
        if (shoppingCart == null){
            shoppingCart = new WxShoppingCart();
            shoppingCart.setAgentId(agent.getId());
            shoppingCart.setCount(count);
            shoppingCart.setCreateTime(new Date());
            shoppingCart.setPrice(price);
            shoppingCart.setSku(colSize.getSku());
            shoppingCart.setProductId(product.getId());
            shoppingCart.setProductName(product.getName());
            shoppingCart.setProductNo(product.getNo());
            shoppingCart.setProductType(product.getTypeId());
            shoppingCart.setTotalPrice(count * price);
            shoppingCart.setColor(colSize.getColor());
            shoppingCart.setSize(colSize.getSize());
            shoppingCart.setChecked(1);
        } else {
            shoppingCart.setCount(shoppingCart.getCount() + count);
            shoppingCart.setTotalPrice(shoppingCart.getTotalPrice() + count * price);
        }
        wxShoppingCartRepository.save(shoppingCart);

        //购物车数量
        List<WxShoppingCart> cartList=wxShoppingCartRepository.findByAgentId(agent.getId());
        Integer cartCount=0;
        for(WxShoppingCart wxShoppingCart:cartList){
            cartCount+=wxShoppingCart.getCount();
        }
        return ResponseUtil.ok(cartCount);
    }



    /****
     * 查找购物车列表
     * @return
     */
    @RequestMapping(value = "findShoppingCart",method = RequestMethod.GET)
    @ResponseBody
    public Object findShoppingCart(String openId){
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        List<WxShoppingCart>cartList = wxShoppingCartRepository.findByAgentId(agent.getId());
        List<Map<String,Object>> list = new ArrayList<>();

        int goodsCount=0;//用户购物车产品数量
        int checkedGoodsCount =0;//勾选选择数量
        int goodsAmount=0;//商品总金额
        int checkedGoodsAmount=0;//勾选商品总金额
        if (cartList.size() > 0){
            for (WxShoppingCart cart : cartList){
                Map<String,Object> subAgentMap = new HashedMap();
                subAgentMap.put("name",cart.getProductName());
                subAgentMap.put("price",cart.getPrice());
                subAgentMap.put("count",cart.getCount());
                subAgentMap.put("cartId",cart.getId());
                subAgentMap.put("color",cart.getColor());
                subAgentMap.put("size",cart.getSize());
                if(cart.getChecked()==0){
                    subAgentMap.put("checked",false);
                }else{
                    subAgentMap.put("checked",true);
                }
                WxProduct product = wxProductRepository.findByNo(cart.getProductNo());
                if (product != null){
                    List<WxProductImage>imageList = wxProductImageRepository.findByProductIdAndIsHomePage(product.getId(),1);
                    subAgentMap.put("image",imageList.get(0).getUrl());
                }
                list.add(subAgentMap);
                //购物车总数据统计
                goodsCount+=1;
                goodsAmount+=cart.getPrice();
                if(cart.getChecked()==1){
                    checkedGoodsCount+=cart.getCount();
                    checkedGoodsAmount+=cart.getTotalPrice();
                }
            }
        }
        //购物车数据统计map
        Map<String, Object> cartTotal = new HashMap<>();
        cartTotal.put("goodsCount",goodsCount);
        cartTotal.put("checkedGoodsCount",checkedGoodsCount);
        cartTotal.put("goodsAmount",new BigDecimal((float)goodsAmount / 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//返回保留两位小数
        cartTotal.put("checkedGoodsAmount",new BigDecimal((float)checkedGoodsAmount / 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        Map<String, Object> result = new HashMap<>();
        result.put("cartTotal",cartTotal);
        result.put("cartList", list);
        return ResponseUtil.ok(result);
    }

    /**
     * 购物车勾选
     * @param data
     * @return
     */
    @RequestMapping("checked")
    @ResponseBody
    public Object checked(@RequestBody String data){
        JSONObject jsonObject=new JSONObject(data);
        if(jsonObject.isNull("cartId")||jsonObject.isNull("isChecked")||jsonObject.isNull("openId")){
            return ResponseUtil.badArgumentValue();
        }
        Integer cartId=jsonObject.getInt("cartId");//购物车产品id
        System.out.println("cartId::::"+cartId);
        Integer checked=jsonObject.getInt("isChecked");//0 false未选择 1 true选择
        System.out.println("checked::::"+checked);
        String openId = jsonObject.getString("openId");
        WxShoppingCart wxShoppingCart=wxShoppingCartRepository.findOne(cartId);
        wxShoppingCart.setChecked(checked);
        wxShoppingCartRepository.save(wxShoppingCart);
        //获取数据
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        List<WxShoppingCart>cartList = wxShoppingCartRepository.findByAgentId(agent.getId());
        List<Map<String,Object>> list = new ArrayList<>();

        int goodsCount=0;//用户购物车产品数量
        int checkedGoodsCount =0;//勾选选择数量
        int goodsAmount=0;//商品总金额
        int checkedGoodsAmount=0;//勾选商品总金额
        if (cartList.size() > 0){
            for (WxShoppingCart cart : cartList){
                Map<String,Object> subAgentMap = new HashedMap();
                subAgentMap.put("name",cart.getProductName());
                subAgentMap.put("price",cart.getPrice());
                subAgentMap.put("count",cart.getCount());
                subAgentMap.put("cartId",cart.getId());
                subAgentMap.put("color",cart.getColor());
                subAgentMap.put("size",cart.getSize());
                if(cart.getChecked()==0){
                    subAgentMap.put("checked",false);
                }else{
                    subAgentMap.put("checked",true);
                }
                WxProduct product = wxProductRepository.findByNo(cart.getProductNo());
                if (product != null){
                    List<WxProductImage>imageList = wxProductImageRepository.findByProductIdAndIsHomePage(product.getId(),1);
                    subAgentMap.put("image",imageList.get(0).getUrl());
                }
                list.add(subAgentMap);
                //购物车总数据统计
                goodsCount+=1;
                goodsAmount+=cart.getTotalPrice();
                if(cart.getChecked()==1){
                    checkedGoodsCount+=1;
                    checkedGoodsAmount+=cart.getTotalPrice();
                }
            }
        }
        //购物车数据统计map
        Map<String, Object> cartTotal = new HashMap<>();
        cartTotal.put("goodsCount",goodsCount);
        cartTotal.put("checkedGoodsCount",checkedGoodsCount);
        cartTotal.put("goodsAmount",new BigDecimal((float)goodsAmount / 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//返回保留两位小数
        cartTotal.put("checkedGoodsAmount",new BigDecimal((float)checkedGoodsAmount / 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        Map<String, Object> result = new HashMap<>();
        result.put("cartTotal",cartTotal);
        result.put("cartList", list);
        return ResponseUtil.ok(result);

    }
    /**
     * 购物车全部勾选
     * @param data
     * @return
     */
    @RequestMapping("checkedAll")
    @ResponseBody
    public Object checkedAll(@RequestBody String data){
        JSONObject jsonObject=new JSONObject(data);
        if(jsonObject.isNull("isChecked")||jsonObject.isNull("openId")){
            return ResponseUtil.badArgumentValue();
        }
        Integer checked=jsonObject.getInt("isChecked");//0 false未选择 1 true选择
        System.out.println("checked::::"+checked);
        String openId = jsonObject.getString("openId");
        //获取数据
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        List<WxShoppingCart>cartList = wxShoppingCartRepository.findByAgentId(agent.getId());
        List<Map<String,Object>> list = new ArrayList<>();

        int goodsCount=0;//用户购物车产品数量
        int checkedGoodsCount =0;//勾选选择数量
        int goodsAmount=0;//商品总金额
        int checkedGoodsAmount=0;//勾选商品总金额
        if (cartList.size() > 0){
            for (WxShoppingCart cart : cartList){
                if(checked==0){
                    cart.setChecked(0);
                }else{
                    cart.setChecked(1);
                }
                wxShoppingCartRepository.save(cart);
                Map<String,Object> subAgentMap = new HashedMap();
                subAgentMap.put("name",cart.getProductName());
                subAgentMap.put("price",cart.getPrice());
                subAgentMap.put("count",cart.getCount());
                subAgentMap.put("cartId",cart.getId());
                subAgentMap.put("color",cart.getColor());
                subAgentMap.put("size",cart.getSize());
                if(cart.getChecked()==0){
                    subAgentMap.put("checked",false);
                }else{
                    subAgentMap.put("checked",true);
                }
                WxProduct product = wxProductRepository.findByNo(cart.getProductNo());
                if (product != null){
                    List<WxProductImage>imageList = wxProductImageRepository.findByProductIdAndIsHomePage(product.getId(),1);
                    subAgentMap.put("image",imageList.get(0).getUrl());
                }
                list.add(subAgentMap);
                //购物车总数据统计
                goodsCount+=1;
                goodsAmount+=cart.getTotalPrice();
                if(cart.getChecked()==1){
                    checkedGoodsCount+=1;
                    checkedGoodsAmount+=cart.getTotalPrice();
                }
            }
        }
        //购物车数据统计map
        Map<String, Object> cartTotal = new HashMap<>();
        cartTotal.put("goodsCount",goodsCount);
        cartTotal.put("checkedGoodsCount",checkedGoodsCount);
        cartTotal.put("goodsAmount",new BigDecimal((float)goodsAmount / 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//返回保留两位小数
        cartTotal.put("checkedGoodsAmount",new BigDecimal((float)checkedGoodsAmount / 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        Map<String, Object> result = new HashMap<>();
        result.put("cartTotal",cartTotal);
        result.put("cartList", list);
        return ResponseUtil.ok(result);

    }
    /**
     * 购物车商品勾选
     * @param data
     * @return
     */
    @RequestMapping("updateCart")
    @ResponseBody
    public Object updateCart(@RequestBody String data){
        JSONObject jsonObject=new JSONObject(data);
        if(jsonObject.isNull("cartId")||jsonObject.isNull("count")||jsonObject.isNull("openId")){
            return ResponseUtil.badArgumentValue();
        }
        Integer cartId=jsonObject.getInt("cartId");//购物车产品id
        System.out.println("cartId::::"+cartId);
        Integer count=jsonObject.getInt("count");//0 false未选择 1 true选择
        System.out.println("count::::"+count);
        String openId = jsonObject.getString("openId");
        WxShoppingCart wxShoppingCart=wxShoppingCartRepository.findOne(cartId);
        wxShoppingCart.setCount(count);
        wxShoppingCartRepository.save(wxShoppingCart);
        //获取数据
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        return ResponseUtil.ok();

    }
    /**
     * 删除购物车商品
     * @param data
     * @return
     */
    @RequestMapping("deleteCart")
    @ResponseBody
    public Object deleteCart(@RequestBody String data){
        JSONObject jsonObject=new JSONObject(data);
        if(jsonObject.isNull("productIds")||jsonObject.isNull("openId")){
            return ResponseUtil.badArgumentValue();
        }
        JSONArray productIds=jsonObject.getJSONArray("productIds");//购物车产品id
        System.out.println("products:::"+productIds.get(0));
        String openId = jsonObject.getString("openId");
        //获取数据
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        for(int i=0;i<productIds.length();i++) {
            Integer productId=(Integer) productIds.get(i);
            System.out.println(productId);
            WxShoppingCart wxShoppingCart=wxShoppingCartRepository.findOne(productId);
            wxShoppingCartRepository.delete(wxShoppingCart);
        }

        List<WxShoppingCart>cartList = wxShoppingCartRepository.findByAgentId(agent.getId());
        List<Map<String,Object>> list = new ArrayList<>();

        int goodsCount=0;//用户购物车产品数量
        int checkedGoodsCount =0;//勾选选择数量
        int goodsAmount=0;//商品总金额
        int checkedGoodsAmount=0;//勾选商品总金额
        if (cartList.size() > 0){
            for (WxShoppingCart cart : cartList){
                wxShoppingCartRepository.save(cart);
                Map<String,Object> subAgentMap = new HashedMap();
                subAgentMap.put("name",cart.getProductName());
                subAgentMap.put("price",cart.getPrice());
                subAgentMap.put("count",cart.getCount());
                subAgentMap.put("cartId",cart.getId());
                subAgentMap.put("color",cart.getColor());
                subAgentMap.put("size",cart.getSize());
                if(cart.getChecked()==0){
                    subAgentMap.put("checked",false);
                }else{
                    subAgentMap.put("checked",true);
                }
                WxProduct product = wxProductRepository.findByNo(cart.getProductNo());
                if (product != null){
                    List<WxProductImage>imageList = wxProductImageRepository.findByProductIdAndIsHomePage(product.getId(),1);
                    subAgentMap.put("image",imageList.get(0).getUrl());
                }
                list.add(subAgentMap);
                //购物车总数据统计
                goodsCount+=1;
                goodsAmount+=cart.getTotalPrice();
                if(cart.getChecked()==1){
                    checkedGoodsCount+=1;
                    checkedGoodsAmount+=cart.getTotalPrice();
                }
            }
        }
        //购物车数据统计map
        Map<String, Object> cartTotal = new HashMap<>();
        cartTotal.put("goodsCount",goodsCount);
        cartTotal.put("checkedGoodsCount",checkedGoodsCount);
        cartTotal.put("goodsAmount",new BigDecimal((float)goodsAmount / 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());//返回保留两位小数
        cartTotal.put("checkedGoodsAmount",new BigDecimal((float)checkedGoodsAmount / 100).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());

        Map<String, Object> result = new HashMap<>();
        result.put("cartTotal",cartTotal);
        result.put("cartList", list);
        return ResponseUtil.ok(result);
    }

    /**
     * 购物车下单
     * @param data
     * @return
     */
    @RequestMapping("checkout")
    @ResponseBody
    public Object checkout(@RequestBody String data){
        JSONObject jsonObject=new JSONObject(data);
        if(jsonObject.isNull("productIds")||jsonObject.isNull("openId")){
            return ResponseUtil.badArgumentValue();
        }
        JSONArray productIds=jsonObject.getJSONArray("productIds");//购物车产品id
        System.out.println("products:::"+productIds.get(0));
        String openId = jsonObject.getString("openId");
        //获取数据
        WxAgent agent = wxAgentRepository.findByOpenId(openId);
        if (agent == null){
            return ResponseUtil.fail(1,"用户不存在");
        }
        //生成未确认订单
        WxOrder wxOrder=new WxOrder();
        wxOrder.setAgentId(agent.getId());
        wxOrder.setCreateTime(new Date());
        wxOrder.setPayStatus(0);//0 未支付
        wxOrder.setStatus(101);//0 未确定订单
        wxOrder.setOrderType(0);//0 商品订单
        wxOrder.setLogisticsFees(0);
        wxOrder.setOrderNumber(OrderNumberUtil.getRandomFileName());
        wxOrderRepository.save(wxOrder);
        Integer totalPrice=0;
        for(int i=0;i<productIds.length();i++) {
            Integer productId=productIds.getJSONObject(i).getInt("cartId");
            System.out.println(productId);
            WxShoppingCart wxShoppingCart=wxShoppingCartRepository.findOne(productId);
            totalPrice+=wxShoppingCart.getTotalPrice();
            //提交订单商品
            WxOrderCommodity wxOrderCommodity=new WxOrderCommodity();
            wxOrderCommodity.setColor(wxShoppingCart.getColor());
            wxOrderCommodity.setCommodityId(wxShoppingCart.getProductId());
            wxOrderCommodity.setCommodityName(wxShoppingCart.getProductName());
            wxOrderCommodity.setCommodityPrice(wxShoppingCart.getPrice());
            wxOrderCommodity.setCount(wxShoppingCart.getCount());
            wxOrderCommodity.setCreateTime(new Date());
            wxOrderCommodity.setOrderId(wxOrder.getId());
            wxOrderCommodity.setSize(wxShoppingCart.getSize());
            wxOrderCommodity.setSku(wxShoppingCart.getSku());
            WxProduct product = wxProductRepository.findByNo(wxShoppingCart.getProductNo());
            if (product != null){
                List<WxProductImage>imageList = wxProductImageRepository.findByProductIdAndIsHomePage(product.getId(),1);
                wxOrderCommodity.setUrl(imageList.get(0).getUrl());
            }else{
                wxOrderCommodity.setUrl("");
            }

            wxOrderCommodity.setType(0);
            wxOrderCommodityRepository.save(wxOrderCommodity);
            wxShoppingCartRepository.delete(wxShoppingCart);
        }
        wxOrder.setTotal(totalPrice);
        wxOrderRepository.save(wxOrder);
        return ResponseUtil.ok(wxOrder.getId());
    }
}
